let deleteLastDot = (inputNode) => {
  // 去掉最后一个小数点
  inputNode.value = inputNode.value.replace(/\.+$/, '')
}

let disablePaste = (event) => {
  event.returnValue = false
  return false
}

let isNaN = (val) => {
  return !/^\d*\.\d*$/.test(val) && !/^\d*$/.test(val) && !/^\d*\.$/.test(val)
}

let getDecimal = (val) => {
  return val.split('.')[1] || ''
}

// 限制小数位，但不补0
let limitDecimal = (val, maxDecimal) => {
  let numberSplit = val.toString().split('.')
  let integer = numberSplit[0]
  let decimal = numberSplit[1] || ''

  if (decimal) {
    decimal = '.' + decimal.slice(0, maxDecimal)
    val = decimal === '.' ? integer : integer + decimal
  }

  return val
}

let getFloat = function (event, val, precision) {
  let newVal = val
  // 非法数字
  if (isNaN) {
    // let _val = parseFloat(val) || ''
    // let isDotExist = false
    // let tmp = []
    // for (let i = 0; i < val.length; i++) {
    //   let char = val.charAt(i)
    //   if (/\d/.test(char)) {
    //     tmp.push(char)
    //     continue
    //   }
    //   if (/\./.test(char) && !isDotExist && i !== 0) { // 添加点号，不能添加第二个点号，开头不能是点号
    //     isDotExist = true
    //     tmp.push(char)
    //   }
    // }
    // val = tmp.join('')
    // newVal = val
    newVal = event.target.lastValue
  }
  // 超过最大小数点
  if (precision && getDecimal(val).length > precision) {
    // let floatReg = new RegExp('^\\d+\\.\\d{' + precision + '}')
    // val = val.match(floatReg)[0]
    // newVal = val
    newVal = event.target.lastValue
  }
  // 不允许小数
  if (precision === 0) {
    // val = val.replace(/\./g, '')
    // newVal = val
    newVal = event.target.lastValue
  }
  return newVal
}

let bind = (vm, inputNode, modelName, precision, cb) => {
  inputNode.addEventListener('paste', disablePaste)
  inputNode.addEventListener('blur', () => {
    deleteLastDot(inputNode)
  })
  inputNode.addEventListener('keydown', (event) => {
    event.target.lastValue = event.target.value // 记住上一次的值
  })
  inputNode.addEventListener('input', (event) => {
    let prec = typeof precision === 'function' ? precision() : precision
    let val = inputNode.value || ''
    let float = val
    if (isNaN(float)) {
      float = getFloat(event, val, prec)
      inputNode.value = float
      vm[modelName] = float
    }
    if (prec > 0 && getDecimal(float).length > prec) {
      float = limitDecimal(float, prec)
      inputNode.value = float
      vm[modelName] = float
    }
    typeof cb === 'function' && cb(float, inputNode.lastValue, event)
  })
}

export default bind
